from collections import OrderedDict


class A:
    def __init__(self, name):
        self.name = name
        # 假设这里存储的是子节点对象和与之关联的数据
        self.children: OrderedDict[str, list[A, int]] = OrderedDict()

    def replace_nodes_by_name(self, target_name, new_node):
        """
        递归地替换具有指定名称的所有节点及其对应的字典键。
        :param target_name: 要替换的目标节点名称
        :param new_node: 新的节点对象
        """
        keys_to_replace = []
        for key, (child, data) in self.children.items():
            if child.name == target_name:
                # 如果找到了匹配的节点，则记录其键以备后续替换
                keys_to_replace.append(key)
            else:
                # 递归调用子节点的replace_nodes_by_name方法
                child.replace_nodes_by_name(target_name, new_node)

        # 替换所有找到的匹配节点及其对应的字典键
        for key in keys_to_replace:
            del self.children[key]
            new_key = new_node.name
            self.children[new_key] = [new_node, data]

    def __str__(self):
        """
        打印树结构，用于调试
        """
        result = f"{self.name} -> {list(self.children.keys())}\n"
        for child, _ in self.children.values():
            result += " " * 4 + str(child)
        return result


# 示例用法
if __name__ == "__main__":
    # 创建示例树结构
    node_a = A("A")
    node_b = A("B")
    node_c = A("C")
    node_d = A("D")
    node_e = A("E")

    node_a.children["B"] = [node_b, 10]
    node_a.children["C"] = [node_c, 20]
    node_b.children["D"] = [node_d, 30]
    node_b.children["E"] = [node_e, 40]

    print("Before replacement:")
    print(node_a)

    # 创建新节点
    new_node = A("NewNode")

    # 替换所有名为 "D" 的节点及其对应的字典键
    node_a.replace_nodes_by_name("D", new_node)

    print("\nAfter replacement:")
    print(node_a)